#include "database.h"
#include "widget.h"
#include "homeroot.h"
#include "ui_homeroot.h"
#include "stuitem.h"
#include <QSqlDatabase>
#include <QSqlError>
#include <QDebug>
#include <QMessageBox>
#include <QString>
#include <QSqlQuery> //用来真正访问操作数据库类
#include <QListWidgetItem>

QString connectDB();
DataBase::DataBase()
{

}

QString DataBase::connectDB()
{
    db = QSqlDatabase::addDatabase("QSQLITE"); //在头文件定义，在这里初始化数据库
    db.setDatabaseName("/home/make/copy/edusystem/edusystem.db");
    if (!db.open()){
        qDebug()<<"openFalse!";
        return "false";
    }
    else {
        qDebug()<<"openSuccess";
        return "true";
    }
}
QString DataBase::logIn_name(QString userid,QString userpassword)
{
    QSqlQuery query; //在创建该对象时，系统会自动完成跟数据库的关联
    QString selectUser = QString("select * from t_user where u_id = '" + userid + "';");
    if(!query.exec(selectUser))
    {
        return "false1";
    }else{
        while(query.next())
        {
            QString u_id = QString(query.value("u_id").toString());
            QString u_pass = QString(query.value("u_password").toString());
            qDebug()<<"u_id"<<u_id;
            qDebug()<<"u_pass"<<u_pass;
            if(u_id == userid && u_pass == userpassword)
            {
                return QString(query.value("u_name").toString());
            }
        }
    }
}

QString DataBase::logIn_per(QString userid,QString userpassword)
{
    QSqlQuery query; //在创建该对象时，系统会自动完成跟数据库的关联
    QString selectUser = QString("select * from t_user where u_id = '" + userid + "';");
    if(!query.exec(selectUser))
    {
        return "false1";
    }else{
        while(query.next())
        {
            QString u_id = QString(query.value("u_id").toString());
            QString u_pass = QString(query.value("u_password").toString());
            qDebug()<<"u_id"<<u_id;
            qDebug()<<"u_pass"<<u_pass;
            if(u_id == userid && u_pass == userpassword)
            {
                return QString(query.value("u_permission").toString());
            }
        }
    }
}

void DataBase::selectStu(StuItem *stu)
{
    QSqlQuery query;
    QString selectStudent = QString("select s_id,s_name,s_sex,s_phone,s_addr from t_student");
    if(query.exec(selectStudent))
    {
        while(query.next())
        {
            QString id = query.value("s_id").toString();
            QString name = query.value("s_name").toString();
            QString sex = query.value("s_sex").toString();
            QString phone = query.value("s_phone").toString();
            QString addr = query.value("s_addr").toString();
            stu->setStuInfo(id,name,sex,phone,addr);
        }
    }else{
        qDebug()<<"error";
    }
}

void DataBase::logOut()
{
    db.close();
}






